package com.hina.rec.common.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 字符串转List类型处理器
 *
 * @author ${USER}
 * @date ${DATE}
 */
@MappedTypes({List.class})
public class StringToListHandler extends BaseTypeHandler<List<?>> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<?> parameter, JdbcType jdbcType) throws SQLException {
        String value = String.join(",", parameter.stream().map(String::valueOf).collect(Collectors.toList()));
        ps.setString(i, value);
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String value = rs.getString(columnName);
        return convertToList(value, columnName);
    }

    @Override
    public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String value = rs.getString(columnIndex);
        return convertToList(value, rs.getMetaData().getColumnName(columnIndex));
    }

    @Override
    public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String value = cs.getString(columnIndex);
        return convertToList(value, cs.getMetaData().getColumnName(columnIndex));
    }

    private List<?> convertToList(String value, String columnName) {
        if (value == null || value.trim().isEmpty()) {
            return null;
        }
        
        // 根据列名判断类型
        if (columnName != null && columnName.toLowerCase().contains("legal_ids")) {
            // 处理legalIds字段，转换为Long类型
            return Arrays.stream(value.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
        } else {
            // 处理其他字段，保持String类型
            return Arrays.asList(value.split(","));
        }
    }
} 